package com.allinpay.mars.common.db.vault.config;

import com.zaxxer.hikari.HikariDataSource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.jdbc.datasource.AbstractDataSource;

import javax.sql.DataSource;
import java.io.Closeable;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author chenzs1
 * @since 2021-12-16
 */
@Slf4j
public class CustomHiKariDatasource extends AbstractDataSource {

    private static final Map<String, HikariDataSource> dataSourceMap = new HashMap<>(1);

    private static final Map<String, Map<String, Object>> tokenMap = new HashMap<>();

    @Override
    public Connection getConnection() throws SQLException {
        return dataSourceMap.get("1").getConnection();
    }

    @Override
    public Connection getConnection(String username, String password) throws SQLException {
        return dataSourceMap.get("1").getConnection(username, password);
    }

    private void destroy() {
        log.info("destroy connection to database");
        DataSource dataSource = dataSourceMap.get("1");
        Closeable closeable = (Closeable) dataSource;
        if (closeable != null) {
            try {
                closeable.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public void updateDataSourceMap(String key, HikariDataSource value) {
        destroy();
        dataSourceMap.put(key, value);
    }

    public void updateTokenMap(String key, Map<String, Object> value) {
        tokenMap.put(key, value);
    }

    public Map<String, Map<String, Object>> getTokenMap() {
        return tokenMap;
    }

    public String getUsername() {
        return (String) tokenMap.get("token").get("username");
    }

    public String getPassword() {
        return (String) tokenMap.get("token").get("password");
    }

}
